using System;
using System.IO;
using System.Net;
using System.Threading;

namespace RStein.Posterous.API
{
    #if SILVERLIGHT
    internal class SLWebClientEx : IWebClient
    {
        #region private variables
        private WebClient m_current;
        #endregion private variables

        #region methods


        public byte[] DownloadData(string fileUrl)
        {

            AsyncHelper.ThrowIfUiThread();
            m_current = new WebClient();

            OpenReadCompletedEventHandler eh = null;
            ManualResetEvent mne = new ManualResetEvent(false);
            byte[] data = null;
            Exception ex = null;

            eh = (o, e) =>
                     {
                         try
                         {
                             var client = e.UserState as WebClient;
                             
                             client.OpenReadCompleted -= eh;
                             if (e.Error != null)
                             {
                                 ex = e.Error;
                                 return;
                             }

                             var ms = new MemoryStream();
                             e.Result.CopyToStream(ms);
                             data = ms.ToArray();

                         }
                         finally
                         {

                             mne.Set();
                         }

                     };


            m_current.OpenReadCompleted += eh;

            m_current.OpenReadAsync(new Uri(fileUrl), m_current);

            mne.WaitOne();

            if (ex != null)
            {
                throw new PosterousException(GlobalConstants.INVALID_RESPONSE_EX, ex);
            }
            return data;
        #endregion methods
        }

        #region Implementation of IWebClientMarker

        public void SetWebClientActions(Action<WebRequest> requestAction, Action<WebResponse> responseAction)
        {

        }

        #endregion
    }
    #endif
}